﻿using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using SqlSugar;

namespace AutoMail.Quartz
{
    public class JobServices : IDisposable, IJobServices
    {
        //调度器
        private IScheduler? _scheduler;

        public JobServices()
        {
            _scheduler = new StdSchedulerFactory().GetScheduler().GetAwaiter().GetResult();
            _scheduler.ListenerManager.AddJobListener(new JobListener(),GroupMatcher<JobKey>.AnyGroup());
        }

        /// <summary>
        /// 创建一个指定时间触发的任务
        /// </summary>
        /// <param name="time">开始时间</param>
        /// <param name="action">委托任务</param>
        /// <returns></returns>
        public async Task CreateJob(DateTimeOffset time, Action action)
        {
            //触发器
            var trigger = TriggerBuilder.Create().StartAt(time).Build();
            //作业
            var job = JobBuilder.Create<TimeWork>()
                .SetJobData(new JobDataMap()
                {
                    new KeyValuePair<string,object>("_Action",action)
                })
                .Build();
            await _scheduler.Start();
            Console.WriteLine("任务开始");
            //添加调度
            await _scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 创建一个指定时间开始，按指定间隔时间轮询执行，永不结束的任务
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="pollTime">间隔时间</param>
        /// <param name="action">委托任务</param>
        /// <returns></returns>
        public async Task CreatePollJob(DateTimeOffset startTime, TimeSpan pollTime, Action action)
        {
            //触发器
            var trigger = TriggerBuilder.Create()
                .WithSimpleSchedule(options =>
                {
                    options.RepeatForever();
                    options.WithInterval(pollTime);
                })
                .StartAt(startTime).Build();
            //作业
            var job = JobBuilder.Create<TimeWork>()
                .SetJobData(new JobDataMap()
                {
                    new KeyValuePair<string,object>("_Action",action)
                })
                .Build();
            await _scheduler.Start();
            Console.WriteLine("任务开始");
            //添加调度
            await _scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 获取所有任务
        /// </summary>
        /// <returns></returns>
        public async Task<List<string>> GetAllJobs()
        {
            var result =(await _scheduler.GetCurrentlyExecutingJobs()).Select(x => x.JobDetail.Key.ToString()).ToList();
            return result;
        }

        public void Dispose()
        {
            //donothing
        }
    }
}